package com.caffeinatedbliss.nanowrimo.servlet;

import com.caffeinatedbliss.nanowrimo.WordWarGraph;
import org.nanowrimo.ws.NanowrimoWebServiceAPI;
import org.nanowrimo.ws.WordCountHandler;
import org.nanowrimo.ws.domain.RegionSummary;
import org.nanowrimo.ws.domain.WordCountSummary;

import javax.imageio.ImageIO;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

public class WordWarGraphServlet extends HttpServlet {
  private int graphWidth;
  private String override;
  private String allowAggregateParam;
  private boolean allowAggregate;
  private String urlFormat;
  private Class<?> handler;
  private int maxEntries;

  public void init(ServletConfig servletConfig) throws ServletException {
    try {
      handler = Class.forName(servletConfig.getInitParameter("handler-class"));
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }

    urlFormat = servletConfig.getInitParameter("url-format");
    override = servletConfig.getInitParameter("override-percentage-complete");
    allowAggregateParam = servletConfig.getInitParameter("allow-aggregate-stats");
    allowAggregate = allowAggregateParam != null && "yes".equals(allowAggregateParam.toLowerCase());
    graphWidth = Integer.parseInt(servletConfig.getInitParameter("graph-width"));
    maxEntries = Integer.parseInt(servletConfig.getInitParameter("max-entries"));
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    UrlProcessor processor = new UrlProcessor(request);
    if (maxEntries != 1) {
      processor.resetParameters(1, 0, 0);
    }
    if (!allowAggregate) {
      processor.resetAggregate(0, 0);
    }
    List uids = processor.getIdList();
    ArrayList<WordCountSummary> summaryList = iCanHasSummariesPlz(uids);

    WordWarGraph graph;
    if (summaryList.size() > 0) {
      String[] names = new String[summaryList.size()];
      int[] amounts = new int[summaryList.size()];
      int[] people = new int[summaryList.size()];
      int goal = 0;
      for (int i = 0; i < summaryList.size(); i++) {
        WordCountSummary summary = summaryList.get(i);
        if (allowAggregate) {
          people[i] = ((RegionSummary) summary).getCount();
        }
        goal = Math.max(goal, summary.getWordcount());
        names[i] = summary.getName();
        amounts[i] = summary.getWordcount();
      }
      if (override != null) {
        if ("yes".equals(override.toLowerCase())) {
          goal = processor.getGoal();
        } else if ("conditional".equals(override.toLowerCase())) {
          goal = (processor.isGoalInUrl()) ? Math.max(processor.getGoal(), goal) : goal;
        }
      }
      graph = new WordWarGraph(goal, graphWidth, names, amounts, people, processor.getWordcountFormat());
    } else {
      String[] names = {"Unknown ID(s)"};
      int[] amounts = {0};
      int[] people = {0};
      graph = new WordWarGraph(1, graphWidth, names, amounts, people, "{0,number,#}");
    }
    response.setContentType("image/png");
    OutputStream os = response.getOutputStream();
    ImageIO.write(graph.getGraphImage(), "png", os);
    os.close();

    // kthxbai
  }

  private ArrayList<WordCountSummary> iCanHasSummariesPlz(List uids) {
    ArrayList<WordCountSummary> summaryList = new ArrayList<WordCountSummary>();
    NanowrimoWebServiceAPI api = new NanowrimoWebServiceAPI();
    int count = 0;
    for (int i = 0; count < maxEntries && i < uids.size(); i++) {
      String uid = (String) uids.get(i);
      int theId = Integer.parseInt(uid);
      try {
        summaryList.add(api.getSummary(theId, urlFormat, (WordCountHandler) handler.newInstance()));
      } catch (InstantiationException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      }
      count++;
    }
    return summaryList;
  }

}
